var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var ejs=require('ejs');
//添加session相关的包
var session = require('express-session');
var bodyparser = require('body-parser');
//导入路由
var userRouter = require('./routes/user');
var adminRouter = require('./routes/admin');
var loginRouter = require('./routes/login');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.html',ejs.__express);
app.set('view engine', 'html');

app.use(bodyparser.json()); // 使用bodyparder中间件，
app.use(bodyparser.urlencoded({ extended: true }));

// 使用 session 中间件
app.use(session({
    secret :  'secret', // 对session id 相关的cookie 进行签名
    resave : true,
    saveUninitialized: false, // 是否保存未初始化的会话
    cookie : {
        maxAge : 1000 * 60 * 30, // 设置 session 的有效时间，单位毫秒
    },
}));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//测试admin路由
app.use('/admin',adminRouter);
//未登录后路由配置
app.use('/check', loginRouter);
// 未登录拦截器
app.use(function (req, res,next) {
  console.log('ip:'+req.ip+'    url:'+req.originalUrl+'   userid:'+req.session.userid);
  if(!req.session.userid){
    return res.redirect('/login.html');
  }
  next();
});
//登录后路由配置
app.use('/', userRouter);
// app.use('/admin',adminRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  console.error(err.stack);
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error.ejs',{message:res.locals.message,stack:err.stack});
});

module.exports = app;
